package com.mall.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.web.reactive.config.ResourceHandlerRegistry;
import org.springframework.web.reactive.config.WebFluxConfigurer;

/**
 * 网关安全配置类
 */
@Configuration
@EnableWebFluxSecurity
public class SecurityConfig implements WebFluxConfigurer {

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        http.authorizeExchange(exchanges -> exchanges
                // 放行Swagger UI相关路径
                .pathMatchers("/swagger-ui.html", 
                              "/swagger-ui/**", 
                              "/v3/api-docs/**", 
                              "/v3/api-docs",
                              "/webjars/**",
                              "/doc.html",
                              "/swagger-resources/**").permitAll()
                // 放行认证相关路径
                .pathMatchers("/auth/login", 
                              "/auth/register", 
                              "/auth/captcha",
                              "/auth/logout").permitAll()
                // 放行第三方登录相关路径
                .pathMatchers("/auth/qr/generate/**",
                              "/auth/qr/check/**",
                              "/auth/oauth2/callback/**").permitAll()
                // 其他路径需要认证
                .anyExchange().authenticated()
        )
        .httpBasic().disable()
        .formLogin().disable()
        .csrf().disable();
        
        return http.build();
    }
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}